<?php

namespace app\api\controller;

use app\api\service\LoginService;
use app\BaseController;
use app\common\service\CommonWechatPayService;
use think\facade\Request;

class Recharge extends BaseController
{

    /*微信充值余额*/
    public function wxRechargBalance(){
        if (Request::isPost()) {
            $user_id = LoginService::getUserIdFromToken();
            if(!is_numeric($user_id)){
                return $user_id;
            }
            $data = $this->request->post();
            try{
                $this->validate($data, 'RechargBalance');
            }catch (\Exception $e){
                return json(['code' => 0, 'msg' => lang($e->getMessage()), 'data' => [], 'count' => '']);
            }
            $payInfo = RechargeService::wxRechargBalanceService($user_id,$data);
            return $payInfo;
        }
    }


    /*微信支付回调*/
    public function wxRechargRoBack(){
        $data = CommonWechatPayService::xmlStructureToArray(file_get_contents('php://input'));
        Cache::set("data",$data,180);
        if ($data['return_code'] == 'SUCCESS' && $data['result_code'] == 'SUCCESS') {
            if(isset($data["attach"]["type"])&&$data["attach"]["type"]==1){
                CommonWechatPayService::wxRechargBalancePayRollBack($data);//支付成功回调处理
            }elseif(isset($data["attach"]["type"])&&$data["attach"]["type"]==2){
                CommonWechatPayService::wxSampleOrderPayRollBack($data);//支付成功回调处理
            }

            echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
            Log::info('微信支付成功！ ' . json_encode($data));
        }else{
            Log::info('微信支付失败！ ' . json_encode($data));
        }
        return Response::wrapData();
    }

}